<template>
  <div class="cfgStrackRunnerbox">
    <el-button @click="handlePrint">打印</el-button>
    <!-- <div>
      <el-button type="primary" size="default" @click='save'>test</el-button>
    </div> -->
    <div style="width: 100%; display: flex; position: relative;">
      <div class="fixedbox flex-all">
        <div class="fixedcontent">
          <div class="icon flex-all">
            <svg t="1624610749718" class="addsvg" viewBox="0 0 1024 1024" @click="addStep" p-id="4803" width="14"
              height="14">
              <path d="M877.216 491.808" p-id="4804" fill="#D3D2D2"></path>
              <path
                d="M575.328 510.496 946.784 140.672c17.568-17.504 17.664-45.824 0.192-63.424-17.504-17.632-45.792-17.664-63.36-0.192L512.032 446.944 143.712 77.216C126.304 59.712 97.92 59.648 80.384 77.12 62.848 94.624 62.816 123.008 80.288 140.576l368.224 369.632L77.216 879.808c-17.568 17.504-17.664 45.824-0.192 63.424 8.736 8.8 20.256 13.216 31.776 13.216 11.424 0 22.848-4.352 31.584-13.056l371.36-369.696 371.68 373.088C892.192 955.616 903.68 960 915.168 960c11.456 0 22.912-4.384 31.648-13.088 17.504-17.504 17.568-45.824 0.096-63.392L575.328 510.496 575.328 510.496zM575.328 510.496"
                p-id="4805" fill="#D3D2D2"></path>
            </svg>
          </div>
          <!-- <el-color-picker class="icon iconpicker flex-all"
          :predefine="predefineColors"
           v-model="color1" @change='changestepColor'>
          </el-color-picker> -->
          <el-select v-model="color1" placeholder="" class="icon iconpicker flex-all" @change='changestepColor'>
            <el-option v-for="item in predefineColors" :key="item" :value="item">
              <span :style="{'color': item}">{{ item}}</span>
            </el-option>
          </el-select>
          <div class="icon  flex-all">
            <svg t="1624610749718" viewBox="0 0 1024 1024" @click="deleteStep" p-id="4803" width="14" height="14">
              <path d="M877.216 491.808" p-id="4804" fill="#D3D2D2"></path>
              <path
                d="M575.328 510.496 946.784 140.672c17.568-17.504 17.664-45.824 0.192-63.424-17.504-17.632-45.792-17.664-63.36-0.192L512.032 446.944 143.712 77.216C126.304 59.712 97.92 59.648 80.384 77.12 62.848 94.624 62.816 123.008 80.288 140.576l368.224 369.632L77.216 879.808c-17.568 17.504-17.664 45.824-0.192 63.424 8.736 8.8 20.256 13.216 31.776 13.216 11.424 0 22.848-4.352 31.584-13.056l371.36-369.696 371.68 373.088C892.192 955.616 903.68 960 915.168 960c11.456 0 22.912-4.384 31.648-13.088 17.504-17.504 17.568-45.824 0.096-63.392L575.328 510.496 575.328 510.496zM575.328 510.496"
                p-id="4805" fill="#D3D2D2"></path>
            </svg>
          </div>
        </div>
      </div>

      <div class="flex leftcontent" ref="leftcontent" @mouseover="changeFlag(false)" @scroll="changeScrollTop">
        <div class="tab-content">
          <el-tree id="tree" class="tree" :data="steps" node-key="id" ref="menuTree" @node-drag-start="handleDragStart"
            draggable @node-drag-end="handleDragend" :allow-drop="allowDrop" @node-click="handleClick">
            <template #default="{ node, data }">
              <span class="ant-input"
                :class="{'box-shadow':currentStep&&data.id==currentStep.id&&data.color!='#FFFFFF','colordeep':currentStep&&data.id==currentStep.id&&data.color=='#FFFFFF'}"
                v-if="data.draggable" draggable="true" @dragstart.stop="dragstartStep(data,$event)"
                @dragend.stop="dragendStep(data,$event)"
                :style="{'background':(data.color),'color':(data.color!='#FFFFFF'?'rgba(255,255,255,.7)':'rgba(51,51,51,.7)')}">{{data.step}}</span>
              <a-input class="ant-input"
                :style="{'background':(data.color),'color':(data.color!='#FFFFFF'?'rgba(255,255,255,.7)':'rgba(51,51,51,.7)')}"
                v-model='data.step' @dblclick.stop='checkStepName(data)' v-else></a-input>
            </template>
          </el-tree>

        </div>
      </div>
      <div id="myDiagramDiv" ref="myDiagramDiv" class="myDiagramDiv" @scroll="scrollFn" @mouseup="scrollEnd">
        <div class="timeline flex-sb" :style='{"width":timelinew}'>
          <span class="time" v-for="item in times">{{item.time}}</span>
          <svg class="arrow" t="1624615241356" viewBox="0 0 1024 1024" p-id="5746" width="16" height="16">
            <path d="M297.603528 121.254245v781.49151l321.764057-195.316428 321.764058-195.542227z" p-id="5747"
              fill="#D3D2D2"></path>
          </svg>
        </div>
        <div class="laneBox" ref='laneBox' @scroll="changeScrollTop1" @mouseover="changeFlag(true)"
          :style='{"width":timelinew}'>
          <canvas id="canvasdrawer" :style='{"width":timelinew}'></canvas>
          <div ref='lanecontent' class="lanecontent" :style='{"width":timelinew}'>
            <div class="laneitem" v-for="(item,index) in steps" :ref="item.id" :style="{'border-color':item.color}">
              <vue-draggable-resizable v-for='(ite,idx) in item.list' :parentData='item' :lableData='ite' :w="50"
                :h="30" :parent="true" :debug="false" :min-width="10" :min-height="40" :isConflictCheck="true"
                :snap="true" :snapTolerance="1" ref="vueDraggableResizable" @resizing='resizingFn'
                @dragging='draggingFn' :x='ite.left' :y='10'>

                <div class="labeltext flex-sb"
                  :style="{'background':(ite.color),'color':(ite.color!='#FFFFFF'?'white':'#333')}"
                  @click.stop="breakLine(ite,item)" @dblclick.stop="showAddLable(ite)"
                  @contextmenu.prevent='deleteLable(item,idx)'>
                  <span v-if="ite.width>40">{{ite.startTime}}</span>
                  <span class="labelname">{{ite.labelname}}</span>
                  <span v-if="ite.width>40">{{ite.endTime}}</span>
                  <svg @click.stop="addLabel(ite)" v-if="ite.showAdd" t="1624610600142" class="addlabel"
                    viewBox="0 0 1024 1024" p-id="2404" width="12" height="12">
                    <path
                      d="M900.7 432.2H548.4V109.3c0-20.2-16.5-36.7-36.7-36.7-20.2 0-36.7 16.5-36.7 36.7v322.9H122.8c-20.2 0-36.7 16.5-36.7 36.7 0 20.2 16.5 36.7 36.7 36.7h352.3v381.6c0 20.2 16.5 36.7 36.7 36.7 20.2 0 36.7-16.5 36.7-36.7V505.6h352.3c20.2 0 36.7-16.5 36.7-36.7-0.1-20.2-16.6-36.7-36.8-36.7z"
                      p-id="2405" fill="#333333"></path>
                  </svg>
                </div>
                <div class="markbox flex">
                  <template v-for="(it,i) in ite.cfgEventCondition">
                    <div v-if="it.candelete">
                      <div class="mark yellowmark" :ref="it.ID" @dblclick="deletemark(i,ite)"
                        @click="getmarkposion(it,ite,item)" v-if="it.isYellow">
                        <span>{{it.text}}</span>
                      </div>
                      <div :ref="it.ID" class="mark" @click="getmarkposion(it,ite,item)" @dblclick="deletemark(i,ite)"
                        v-else>
                        <span>{{it.text}}</span></v-else>
                      </div>
                    </div>
                    <div v-else>
                      <input type="number" v-model="it.text" @blur="candeleteFn(it,ite)"
                        @keyup.enter="candeleteFn(it,ite)" class="mark markinput yellowmark,ite" v-if="it.isYellow" />
                      <input type="number" v-model="it.text" @blur="candeleteFn(it,ite)"
                        @keyup.enter="candeleteFn(it,ite)" class="mark markinput" v-else />
                    </div>
                  </template>
                </div>
              </vue-draggable-resizable>
              <!-- </div> -->
            </div>
          </div>
        </div>
      </div>
      <div class="editebox">
        <div class="editeboxtitle">组合动作编辑</div>
        <div v-if="currentLable" class="editecontent">
          <div class="flex-sb">
            <span>动作编号</span>
            <span class="a-input">{{currentStep.ID}}</span>
            <!-- <a-input class='a-input' type="number" :min="1" :max="steps.length" @change='changeStepIndex'
              v-model='currentStep.ID'></a-input> -->
          </div>
          <div class="flex-sb">
            <span>动作名称</span>
            <a-input class='a-input' v-model='currentLable.name'></a-input>
          </div>
          <el-collapse accordion class="el-collapse" v-if="currentLable">
            <el-collapse-item v-for="(item,index) in currentLable.cfgEventCondition">
              <template slot="title">
                条件{{index*1+1}}
              </template>
              <div class="flex-sb" style="margin-bottom: 6px;">
                <span>条件类型</span>
                <a-select v-model="item.TypeID" style="width: 110px;position:relative"
                  @change="((val)=>{chooseFn(val, item)})">
                  <a-select-option :value="k" :key="k" v-for="(item,k) in enCombinedActConditionType">{{item.name}}
                  </a-select-option>
                </a-select>
              </div>
              <div class="flex-sb">
                <span>最大超时</span>
                <a-input type='number' v-model="item.maxTimeout100MS" :min="1" :max="10"></a-input>
              </div>
              <el-collapse>
                <el-collapse-item v-for="(ite,idx) in item.handlerDefines">
                  <template slot="title">
                    执行器{{idx*1+1}}
                  </template>
                  <div class="flex-sb">
                    <span>执行器类型</span>
                    <a-select :default-value="ite.TypeID" style="width: 110px;position:relative" @change="chooseFn1">
                      <a-select-option v-for="(item,k) in enCombinedHandlerType" :value="k">{{item.name}}
                      </a-select-option>
                    </a-select>
                  </div>
                  <div class="flex-sb">
                    <span>执行器数据</span>
                    <a-select :default-value="ite.Data" mode="multiple" style="width: 110px;position:relative">
                      <a-select-option v-for="(item,k) in enActionCode" :value="item.key">{{item.key}}
                      </a-select-option>
                    </a-select>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-collapse-item>
          </el-collapse>
          <div class="flex-sb">
            <span>起始时间</span>
            <span>{{currentLable.startTime}}~{{currentLable.endTime}}</span>
          </div>
        </div>
      </div>


    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import VueDraggableResizable from '../../../components/draggable-resizable/vue-draggable-resizable.vue'
  import '../../../components/draggable-resizable/vue-draggable-resizable.css'
  import colors from "./utils/colors.js"
  import enCombinedActConditionType from './data/enCombinedActConditionType.js'
  import enParaID from './data/enParaID.js'
  import enCombinedHandlerType from './data/enCombinedHandlerType.js'
  import enActionCode from './data/enActionCode.js'
  import stepActions from './data/stepActions.js'

  export default {
    components: {
      VueDraggableResizable,
    },
    data() {
      return {
        predefineColors: colors, //预设置颜色集合
        enCombinedActConditionType: enCombinedActConditionType,
        enParaID: enParaID,
        enCombinedHandlerType: enCombinedHandlerType,
        enActionCode: enActionCode,
        midscrollFlag: false, //判断是否在滚动中间的左右滚动条
        scrollFlag: false, //监听是滚动哪个滚动条
        mkLine: null,
        ctx: null, //canvas画线
        canvas: null,
        timelinew: '520px', //默认时间线
        lines: [], //连线集合
        canvaswidth: '',
        lastLineTip: null, //上一个点击的黄色按钮
        connList: [],
        poolList: [],
        steps: stepActions.mock,
        times: [],
        currentStep: null, //当前工步
        currentLablePos: null, //泳道内当前标签移动位置
        currentMark: null, //当前事件
        color1: 'red',
        currentLable: null,
        laneBoxWidth: '', //中间区域宽度
        baseW: 2, //每两个像素为0.1s
        beforeScroll: null, //滚动位置
      }
    },
    mounted() {
      this.canvas = document.getElementById('canvasdrawer');
      this.setTimeline(Math.ceil(520 / this.baseW)) //默认520个像素
      this.beforeScroll = this.$refs.myDiagramDiv.scrollLeft;
      if (this.steps.length > 0) {
        this.steps.forEach((item, index) => {
          if (item.list && item.list.length > 0) {
            let endTime = item.list.reduce((num1, num2) => {
              return num1.endTime > num2.endTime ? num1.endTime : num2.endTime
            })
            console.log(endTime, 326)
          }
        })
      }
      if (this.lines.length > 0) { //当存在数据连线功能时
        this.readyPigment()
      }
    },

    methods: {
      handlePrint() {
        console.log(JSON.stringify(this.steps));
        console.log(this.steps);
      },
      changeFlag(flag) { //判断当前滚动的滚动条
        this.scrollFlag = flag
      },
      changeScrollTop(e) { //监听左侧滚动条同步中间
        if (!this.scrollFlag) {
          this.$refs.laneBox.scrollTop = this.$refs.leftcontent.scrollTop;
        }
      },
      changeScrollTop1(e) { //监听中间滚动条同步左侧
        if (this.scrollFlag) {
          this.$refs.leftcontent.scrollTop = this.$refs.laneBox.scrollTop;
        }
      },
      scrollFn(e) { //横向滚动中间部分增加画布宽度
        let offsetWidth = e.target.offsetWidth,
          scrollWidth = e.target.scrollWidth,
          scrollLeft = e.target.scrollLeft;
        let delta = scrollLeft - this.beforeScroll;
        if (delta === 0) return false;
        if (delta > 0) {
          this.midscrollFlag = true
          let timelinew = parseFloat(this.timelinew)
          timelinew += 5;
          this.timelinew = timelinew + 'px'
          this.setTimeline(Math.ceil(timelinew / this.baseW));
        }
        this.beforeScroll = scrollLeft;
      },
      scrollEnd() {
        if (this.midscrollFlag) { //当滚动条不往右滚动了就重绘连线图
          this.readyPigment()
          this.midscrollFlag = false;
        }
      },
      setTimeline(t) { //设置时间线
        let arr = [];
        for (let i = 0; i <= t; i++) {
          if (i % 50 == 0) {
            let obj = {
              time: i / 10
            }
            arr.push(obj)
          }
        }
        this.times = arr;
      },
      readyPigment() {
        this.canvas.width = this.$refs.lanecontent.clientWidth
        this.canvas.height = this.$refs.lanecontent.clientHeight
        this.ctx = this.canvas.getContext('2d');
        const lines = this.lines;

        const inter = setInterval(() => {
          if (this.ctx) {
            clearInterval(inter)
            this.cleanCvs(); //清空
            if (lines.length > 0) {
              lines.forEach(item => {
                this.drawLineArrow(item.x1, item.y1, item.x2, item.y2, '#333333')
              })
            } else {
              this.cleanCvs()
            }
          }
        }, 100)
      },
      // 清除画布
      cleanCvs() {
        // 重置渲染上下文并清空画布
        this.ctx.save();
        this.ctx.setTransform(1, 0, 0, 1, 0, 0);
        this.ctx.clearRect(0, 0, this.ctx.canvas.offsetWidth, this.ctx.canvas.offsetHeight);
        // 恢复先前渲染上下文所进行的变换
        this.ctx.restore();
      },

      /**
       * 绘制带有箭头的直线
       * @param fromX/fromY 起点坐标
       * @param toX/toY 终点坐标
       * @param color 线与箭头颜色
       **/
      drawLineArrow(fromX, fromY, toX, toY, color) {
        let midX = null,
          midY = null,
          midX1 = null, //加多一个拐角
          midY1 = null;

        if (fromY == toY) { //当在一条水平线上时坐标点集体向下移动6个像素
          fromY += 14;
          toY += 14;
          fromX += 6;
          toX += 6
          midX = toX;
          midY = toY + 6;
          midX1 = fromX;
          midY1 = fromY + 6
        } else if (fromX == toX) { //当起点和终点在一个Y轴上时
          if (fromY < toY) { //起点在上面时
            fromY += 14;
          } else {
            toY += 12;
          }
          fromX += 6;
          toX += 6;
        } else { //起点和终点都不在一个Y轴和X轴上
          if (fromY < toY) { //起点在上面时
            fromY += 14;
            fromX += 6;
            if (fromX < toX) {
              toX += 6
            } else {
              toX += 6
            }
            toY += 6;
            midX = toX;
            midY = toY + 14;
            midX1 = fromX;
            midY1 = toY + 14
          } else { //起点在下面时
            if (fromX > toX) {
              toY += 14;
              toX += 6;
              fromY += 14;
              fromX += 6;
            } else {
              toY += 14;
              toX += 6;
              fromY += 14;
              fromX += 6;
            }
            midX = toX;
            midY = fromY + 14;
            midX1 = fromX
            midY1 = midY
          }
        }

        var headlen = 5; //自定义箭头线的长度
        var theta = 135; //自定义箭头线与直线的夹角，个人觉得45°刚刚好
        var arrowX, arrowY; //箭头线终点坐标
        // 计算各角度和对应的箭头终点坐标
        var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI;
        if (midX) { //当中间点存在时更改箭头角度
          angle = Math.atan2(fromY - midY1, fromX - midX1) * 180 / Math.PI;
        }
        var angle1 = (angle + theta) * Math.PI / 180;
        var angle2 = (angle - theta) * Math.PI / 180;
        var topX = headlen * Math.cos(angle1);
        var topY = headlen * Math.sin(angle1);
        var botX = headlen * Math.cos(angle2);
        var botY = headlen * Math.sin(angle2);

        this.ctx.beginPath();
        //画直线
        this.ctx.moveTo(fromX, fromY);
        if (midX) {
          this.ctx.lineTo(midX1, midY1);
          this.ctx.lineTo(midX, midY);
        }
        this.ctx.lineTo(toX, toY);

        //画上边箭头线
        arrowX = fromX + topX;
        arrowY = fromY + topY;
        this.ctx.moveTo(arrowX, arrowY);
        this.ctx.lineTo(fromX, fromY);

        //画下边箭头线
        arrowX = fromX + botX;
        arrowY = fromY + botY;
        this.ctx.lineTo(arrowX, arrowY);
        this.ctx.strokeStyle = color;
        this.ctx.lineWidth = 1;
        this.ctx.stroke();
      },
      save() {
        console.log(this.steps)
      },
      onSelect(e) {
        console.log(e, 'onSelect')
      },
      onExpand(e) {
        console.log(e, 'onExpand')
      },
      changeStepIndex(e) { //更改工步位置
        let steps = this.steps;
        if (this.currentStep.index > steps.length || e.data && parseFloat(e.data) > steps.length) {
          this.currentStep.index = steps.length
        }
        console.log(this.currentStep.index, 228, e)
        if (steps.length == 1) {
          return
        }
        let i = this.steps.findIndex(d => d.id === this.currentStep.id);
        this.steps = this.Move(this.steps, i, this.currentStep.index * 1 - 1)
      },
      chooseFn(e, data) { //更改条件
        // console.log(e, data, 230, this.currentMark)
        if (e == "enCombinedCondition_REFER") { //更改事件是否为黄色
          data.isYellow = true;
        } else {
          data.isYellow = false;
        }
        data.TypeID = e;
        let lines = this.lines;
        let i = lines.findIndex(d => d.resouceId === data.ID);
        let j = lines.findIndex(d => d.targetId === data.ID);
        if (this.lastLineTip && this.lastLineTip.resouceId == data.ID) { //当黄色变灰色
          this.lastLineTip = null
        }
        if (i >= 0) {
          lines.splice(i, 1)
        }
        if (j >= 0) {
          lines.splice(j, 1)
        }
        this.readyPigment()
      },
      chooseFn1(e) { //更改条件
        console.log(e, 231)
      },
      // 判断鼠标是否落在一个块级元素内部
      checkIn(obj) {
        var x = Number(window.event.clientX) // 鼠标相对屏幕横坐标
        var y = Number(window.event.clientY) // 鼠标相对屏幕纵坐标

        var div_x = Number(obj.getBoundingClientRect().left) // obj相对屏幕的横坐标
        var div_x_width = Number(
          obj.getBoundingClientRect().left + obj.clientWidth
        ) // obj相对屏幕的横坐标+width

        var div_y = Number(obj.getBoundingClientRect().top) // obj相对屏幕的纵坐标
        var div_y_height = Number(
          obj.getBoundingClientRect().top + obj.clientHeight
        ) // obj相对屏幕的纵坐标+height

        if (x > div_x && x < div_x_width && y > div_y && y < div_y_height) {
          return true
        } else {
          return false
        }
      },
      deletemark(i, data) { //删除事件
        console.log(i, data, 'deletemark')
        this.$confirm('此操作会将该事件删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(data, 516)
          this.resetLine(data.cfgEventCondition[i])
          data.cfgEventCondition.splice(i, 1)
          this.steps = [...this.steps]
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      resetLine(data) {
        let lines = this.lines;
        let i = lines.findIndex(d => d.resouceId === data.ID);
        let j = lines.findIndex(d => d.targetId === data.ID);
        if (i >= 0) {
          lines.splice(i, 1)
        }
        if (j >= 0) {
          lines.splice(j, 1)
        }
        this.lines = lines
        this.readyPigment()
      },
      candeleteFn(data, pdata) { //确认输入完成事件控制数量

        if (parseFloat(data.text) >= 1) {
          data.candelete = true;
          let handlerDefines = JSON.parse(JSON.stringify(stepActions.handlerDefines))
          let obj = {
            ...handlerDefines
          };
          let list = [];
          for (let i = 0; i < data.text * 1; i++) {
            list.push(obj)
          }
          data.handlerDefines = list;
        }
        this.steps = [...this.steps]
        this.currentMark = data;
        pdata.showAdd = false;
        this.$nextTick(() => {
          this.changePosition(pdata)
        })
      },

      returnMarkPosition(id) { //计算mark事件的位置信息
        let mleft = this.$refs[id][0].getBoundingClientRect().x;
        let mtop = this.$refs[id][0].getBoundingClientRect().y;
        let laneBoxL = this.$refs.lanecontent.getBoundingClientRect().x;
        let laneBoxT = this.$refs.lanecontent.getBoundingClientRect().y;
        return {
          left: Number(mleft - laneBoxL),
          top: Number(mtop - laneBoxT)
        }
      },
      getmarkposion(data, labledata, stepdata) {
        this.currentMark = data;
        this.currentLable = labledata;
        this.currentStep = stepdata;
        labledata.showAdd = false;
        console.log(data, labledata, stepdata, 21888)
        let pos = this.returnMarkPosition(data.ID);
        let lines = this.lines;
        if (labledata.list && labledata.list.length > 0) { //
          let num = 0;
          labledata.list.forEach((item, i) => {
            if (item.ID == data.ID) {
              console.log(item, 574);
              pos.top = pos.top * 1 + i * 2
            }
          })

        }
        if (data.isYellow) {
          let obj = {
            id: 'line' + new Date().getTime(),
            resouceId: data.ID,
            x1: pos.left,
            y1: pos.top
          }

          this.lastLineTip = obj;
          if (lines.length > 0) {
            let i = lines.findIndex(d => d.resouceId === data.ID);
            if (i < 0) {
              lines.push(obj)
            }
          } else {
            lines.push(obj)
          }
          // .push(obj)
        } else {
          if (!this.lastLineTip) {
            this.lastLineTip = null;
            return
          }
          let j = lines.findIndex(d => d.resouceId === this.lastLineTip.resouceId); //找到最后一个黄标在线数组中的位置
          if (j >= 0) {
            lines[j].targetId = data.ID; //将灰标位置等相关信息传递放进线数组
            lines[j].x2 = pos.left;
            lines[j].y2 = pos.top;
            this.lines = lines;
            this.readyPigment() //调用画图
          }
        }
        this.$forceUpdate();
      },
      addLabel(data) { //点击增加事件
        let condition = JSON.parse(JSON.stringify(stepActions.condition))
        condition.ID = 'mark' + new Date().getTime();
        console.log(condition, 617);
        let obj = {
          ...condition,
          // isYellow: false,
          // id: 'mark' + new Date().getTime(),
          // text: 1,
          // condition: '空事件',
          // cfgEventCondition: [...stepActions.condition],
          // candelete: false,
        }
        data.cfgEventCondition.push(obj)
        this.currentMark = obj;
        this.$nextTick(() => {
          this.changePosition(data)
        })
      },
      breakLine(data, pdata) { //停止连线功能
        this.lastLineTip = null;
        this.currentLable = data;
        this.currentStep = pdata;
        this.currentMark = null
      },
      showAddLable(data) { //显示添加事件的加号
        data.showAdd = !data.showAdd;
        this.steps = [...this.steps]
        console.log(data, 2222, this.steps)
      },
      deleteLable(data, i) { //删除label
        this.$confirm('此操作会将该动作删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          let list = data.list[i];
          if (list.cfgEventCondition && list.cfgEventCondition.length > 0) {
            list.cfgEventCondition.forEach(ite => {
              this.resetLine(ite)
            })
          }
          data.list.splice(i, 1);
          this.steps = [...this.steps]
          this.currentLable = null;
          this.currentMark = null;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      dragstartStep(data, e) {
        console.log(data, e, 'dragstartStep')
      },
      dragendStep(data, e) {
        let i = this.steps.findIndex(d => d.id === data.id);
        let lableref = this.$refs[data.id][0];
        if (this.checkIn(lableref)) {
          var x = Number(window.event.clientX) // 鼠标相对屏幕横坐标
          var y = Number(window.event.clientY) // 鼠标相对屏幕纵坐标
          var div_x = Number(lableref.getBoundingClientRect().left) // lableref相对屏幕的横坐标
          let startTime = Math.abs(div_x - x) > 0 ? (parseFloat((Math.abs(div_x - x) / this.baseW) / 10)).toFixed(1) :
            0;
          let element = JSON.parse(JSON.stringify(stepActions.element))
          let obj = {
            ...element,
            color: data.color,
            startTime: startTime,
            endTime: (startTime * 1 + 1).toFixed(1),
            left: Math.abs(div_x - x),
            top: '10',
            width: 60,
          }
          obj.ID = 'label' + new Date().getTime();
          this.steps[i].list.push(obj)
          this.currentLable = obj;
        }
      },
      resizingFn(l, t, w, h, data, pdata) {
        this.setLable(l, data, pdata, w)
        this.changePosition(data)
      },
      draggingFn(l, t, w, h, data, pdata) {
        this.setLable(l, data, pdata, w)
        this.changePosition(data)
      },
      changePosition(data) { //拖动或者拉伸时，重新计算的位置信息
        if (data.cfgEventCondition && data.cfgEventCondition.length > 0) {
          let lines = this.lines;
          data.cfgEventCondition.forEach(item => {
            lines.forEach(ite => {
              console.log(item, ite, 681);
              if (item.ID == ite.targetId) {
                let pos = this.returnMarkPosition(item.ID);
                ite.x2 = pos.left;
                ite.y2 = pos.top;
              }
              if (item.ID == ite.resouceId) {
                let pos = this.returnMarkPosition(item.ID);
                ite.x1 = pos.left;
                ite.y1 = pos.top;
              }
            })
          })
          this.lines = lines;
          this.readyPigment() //调用画图
        }
      },
      setLable(l, data, parentData, w) { //设置lable位置宽度等信息
        data.top = '10';
        data.left = l;
        data.startTime = l > 0 ? ((l / this.baseW) / 10).toFixed(1) : 0
        w = w > (this.baseW * 5) ? w : this.baseW * 5;
        data.width = w;
        data.endTime = (data.startTime * 1 + (w / this.baseW) / 10).toFixed(1)
        console.log(w, 7777777, data.endTime)
        this.currentLable = data;
        this.currentStep = parentData;
        this.currentMark = null;
      },
      checkStepName(data) { //更改当前工步名称
        console.log(data, 2334)
        data.draggable = true
      },
      handleClick(data, node) { //选择当前工步信息
        this.currentStep = data;
        this.currentLablePos = null;
        this.currentLable = null;
        this.currentMark = null;
        if (data.step == '') {
          this.currentStep.draggable = false
        }
      },
      changestepColor(e) { //更改工步背景色
        console.log(e, 721)
        if (!this.currentStep) {
          this.$message({
            type: 'info',
            message: '请选择工步'
          });
          return;
        }
        this.currentStep.color = e;
        let steps = this.steps;
        steps.forEach(item => {
          if (item.id == this.currentStep.id) {
            item.color = e;
            if (item.list && item.list.length > 0) {
              item.list.forEach(ite => {
                ite.color = e
              })
            }
          }
        })
        this.steps = steps
      },
      addStep() { //增加工步
        let index = (this.steps.length * 1 + 1) + ''
        let stepItem = JSON.parse(JSON.stringify(stepActions.stepItem))
        let obj = {
          ...stepItem,
          index
        }
        console.log(obj, 707, stepActions.stepItem)
        obj.id = 'step' + new Date().getTime();
        this.steps.push(obj);
        this.currentStep = obj;
        this.currentMark = null;
        this.readyPigment()
      },
      getRandomColor() {
        var str = "#";
        var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
        for (var i = 0; i < 6; i++) {
          var num = parseInt(Math.random() * 16);
          str += arr[num];
        }
        return str;
      },
      deleteStep() { //删除工步
        // console.log('deleteStep')
        if (!this.currentStep) {
          this.$message({
            type: 'info',
            message: '请选择要删除的工步'
          });
          return;
        }
        let i = this.steps.findIndex(d => d.id === this.currentStep.id);
        this.$confirm('此操作会将该工步删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let list = this.steps[i];
          if (list.list && list.list.length > 0) {
            list.list.forEach(item => {
              if (item.cfgEventCondition && item.cfgEventCondition.length > 0) {
                item.cfgEventCondition.forEach(ite => {
                  this.resetLine(ite)
                })
              }

            })
          }
          this.steps.splice(i, 1)
          this.currentStep = null;
          this.currentMark = null;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleDragStart(node, ev) { //拖动左侧工步
        // console.log('handleDragStart')
      },
      handleDragend(draggingNode, endNode, position, event) {
        // console.log('handleDragend', draggingNode, endNode, position, event)
      },

      Move(arr, a, b) { //更改泳道位置信息
        let arr_temp = [].concat(arr); //创建一个新的临时数组，用以操作后不变更原数组
        arr_temp.splice(b, 0, arr_temp.splice(a, 1)[0]); //在b位置插入从a位置截取的元素
        return arr_temp;
      },
      allowDrop(draggingNode, dropNode, type) { //不可拖动到里面
        return type !== 'inner';
      }

    },
    created() {
      
    }
  }
</script>

<style lang="less">
  .cfgStrackRunnerbox {
    position: relative;

    .ant-select ul {
      display: none;
    }

    .el-input--suffix .el-input__inner {
      display: none;
    }

    .el-select .el-input .el-select__caret {
      display: none;
    }

    .canvas {
      position: absolute;
      z-index: 0;
    }

    .myDiagramDiv {
      width: 520px;
      overflow-x: scroll;
      position: relative;
    }

    .iconpicker {
      width: 30px;
      height: 30px;

      .el-input.is-focus .el-input__inner {
        border: 0;
      }
    }

    .timeline {
      position: relative;
      font-size: 12px;
      height: 18px;

      .arrow {
        position: absolute;
        right: -10px;
        bottom: -8px;
      }
    }

    .laneBox {
      position: relative;
      flex-grow: 1;
      height: 482px;
      background-color: #fff;
      margin: 0 4px;
      overflow-y: scroll;
      overflow-x: hidden;
    }

    .lanecontent {
      position: absolute;
      top: 0;
      z-index: 2;
      min-height: 482px;
      padding-bottom: 10px;
    }

    .el-color-picker__trigger {
      width: 20px;
      height: 20px;
      border: 0;
    }

    .fixedbox {
      position: absolute;
      top: 40%;
      left: 6px;
      z-index: 2;

      .icon {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        border: 1px solid #D3D2D2;
        margin-bottom: 6px;

        .addsvg {
          transform: rotate(45deg);
        }
      }

    }

    .leftcontent {
      position: relative;
      width: 135px;
      height: 482px;
      margin-top: 18px;
      margin-right: 2px;
      background-color: whitesmoke;
      border: solid 1px black;
      overflow-y: scroll;
      overflow-x: hidden;
      padding-left: 30px;
      box-sizing: border-box;

      .el-tree {
        background-color: transparent;
        padding-bottom: 10px;
      }

      .el-tree-node__expand-icon.is-leaf {
        cursor: pointer;
        width: 4px;
      }

      .el-tree-node {
        padding-top: 10px;
        height: 70px;
        padding-right: 4px;
        box-sizing: border-box;
      }
    }

    .leftcontent::-webkit-scrollbar,
    .laneBox::-webkit-scrollbar,
    .editecontent::-webkit-scrollbar {
      /*滚动条整体样式*/
      width: 4px;
      /*高宽分别对应横竖滚动条的尺寸*/
    }

    .leftcontent::-webkit-scrollbar-thumb,
    .laneBox::-webkit-scrollbar-thumb,
    .editecontent::-webkit-scrollbar-thumb {
      /*滚动条里面小方块*/
      border-radius: 2px;
      background: #aaa;
    }

    .leftcontent::-webkit-scrollbar-track,
    .laneBox::-webkit-scrollbar-track,
    .editecontent::-webkit-scrollbar-track {
      /*滚动条里面轨道*/
      border-radius: 4px;
      background: transparent;
    }

    .flex-all {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .flex-sb {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .flex {
      display: flex;
    }

    .flex_center {
      align-items: center;
    }

    .wrapper {
      display: flex;
      /* align-items: center; */
      /* justify-content: center; */
      width: 100%;
    }

    .card_item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 5px 0;
      font-size: 12px;
      border-bottom: 1px solid #f6f6f6;
    }

    .card_item+.card_item {
      margin-top: 8px;
    }

    .laneitem {
      height: 70px;
      // border: 1px solid transparent;
      position: relative;

      .lanelabel {
        position: absolute;

      }

      .labeltext {
        border-radius: 6px;
        height: 36px;
        padding: 2px;
        box-sizing: border-box;
        opacity: .8;
        font-size: 12px;

        .labelname {
          flex: 1;
          text-align: center;
          display: inline-block;
          padding: 0 2px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        span:last-child {
          display: inline-block;
          padding-left: 4px;
        }
      }

      .addlabel {
        position: absolute;
        right: -8px;
        z-index: 4;
        top: -4px;
      }

      .markbox {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        top: 40px;

        .mark {
          width: 14px;
          height: 14px;
          border-radius: 4px;
          text-align: center;
          line-height: 14px;
          font-size: 12px;
          border: 0;
          background-color: rgba(158, 158, 158, .9);
          color: #333;
          margin-right: 4px;

          span {
            transform: scale(.8);
            display: block;
          }
        }

        .yellowmark {
          background-color: rgba(255, 251, 0, .8);
        }

        .markinput {
          width: 40px;
        }
      }
    }

    .el-tree-node__content {
      height: 40px;
    }

    .ant-input {
      text-align: center;
      width: 80px;
      line-height: 22px;
      height: 36px;
      padding-top: 6px;
      padding-bottom: 6px;
      opacity: .8;
    }

    .box-shadow {
      color: rgba(255, 255, 255, 1) !important;
    }

    .colordeep {
      color: rgba(51, 51, 51, 1) !important;
    }

    .editebox {
      min-width: 300px;
      padding: 0 10px;
      margin-left: 10px;

      .editecontent {
        height: 482px;
        background-color: #fff;
        padding: 10px;
        overflow-y: scroll;
        overflow-x: hidden;
        box-sizing: border-box;

        .flex-sb {
          height: 40px;
        }
      }

      .ant-select-selection {
        margin-left: 4px;
      }

      .editeboxtitle {
        text-align: center;
        line-height: 18px;
      }

      .a-input {}

      .el-collapse-item__header {
        background-color: transparent;
        position: relative;
        padding-left: 20px;
        box-sizing: border-box;
        border-bottom: 0;
      }

      .el-collapse-item__wrap {
        background-color: transparent;
        padding-left: 20px;
        box-sizing: border-box;
        font-size: 14px;
        border: 0;
      }

      .el-collapse {
        border: 0;
      }

      .el-collapse-item__arrow {
        position: absolute;
        top: 50%;
        left: 4px;
        transform: translateY(-50%);
      }
    }
  }
</style>
